package today.rocky.boot.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Rocky
 * @date 2020/2/18 17:13
 */
@RestController
@RequestMapping("/redis")
public class PublishController {

   private RedisTemplate<String, String> redisTemplate;

   @Autowired
    public PublishController(RedisTemplate<String, String> redisTemplate){
       this.redisTemplate = redisTemplate;
    }



    @RequestMapping("/create")
    public String createList(){
       redisTemplate.opsForList().leftPushAll("seckill:1001",new String[]{"1","1","1","1","1"});
       return "success";
    }

    @RequestMapping("/secKill")
    public String secKill(){
       String s = redisTemplate.opsForList().rightPop("seckill:1001");
       if (s!=null){
           return Thread.currentThread().getName()+"抢到了";
       }else {
           return Thread.currentThread().getName()+"没抢到";
       }
    }

    @RequestMapping("/lock/secKill")
    public String lockSecKill(){
        redisTemplate.opsForValue().setIfAbsent("seckill",Thread.currentThread().getName());
        String s = redisTemplate.opsForList().rightPop("seckill:1001");
        if (s!=null){
            String tName = redisTemplate.opsForValue().get("secKill");
            if (Thread.currentThread().getName().equals(tName)){
                redisTemplate.delete("seckill");
            }
            return Thread.currentThread().getName()+"抢到了";
        }else {
            String tName = redisTemplate.opsForValue().get("secKill");
            if (Thread.currentThread().getName().equals(tName)){
                redisTemplate.delete("seckill");
            }
            return Thread.currentThread().getName()+"没抢到";
        }
    }


}
